package jee.boot.oauth.config.token;

import jee.boot.common.properties.ProjectConfig;
import jee.boot.common.utils.SpringContextHolder;
import jee.boot.common.utils.StringUtils;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 自定义拓展token生成策略,增加构造token的参数
 */
public class CustomAuthenticationKeyGenerator extends DefaultAuthenticationKeyGenerator {

    @Override
    protected String generateKey(Map<String, String> values) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String realIp = request.getHeader("x-real-ip");
        ProjectConfig projectConfig = SpringContextHolder.getApplicationContext().getBean(ProjectConfig.class);
        // 添加客户主机的真实ip
        if(projectConfig.isAddRealIpToToken()&&StringUtils.isNotBlank(realIp)){
            values.put("realIp",realIp);
        }
        String projectName = projectConfig.getName();
        // 添加本机服务名称
        if(StringUtils.isNotBlank(projectName)){
            values.put("projectName",projectName);
        }
        return super.generateKey(values);
    }
}
